from django.conf import settings
from django.contrib.auth.models import ContentType
from django.contrib.auth.models import Permission
from django.http import JsonResponse
from django.shortcuts import render, reverse, redirect
from django.views import View
from itsdangerous import SignatureExpired
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from account.models import User
from account.models import UserAddress
from utils.decorators import login_required
from utils.email import send_active_email
from utils.gencode import gen_base64_verify_code_img
from utils.hashers import make_password, check_password


def index(request):
    return JsonResponse({'message': 'Hello!'})


class VerifyCode(View):
    def get(self, request):
        """获得验证码"""
        base64_img, verification_code = gen_base64_verify_code_img()
        print(verification_code)
        request.session['verification_code'] = verification_code
        # send_code_by_aliyun(phone)
        return JsonResponse({"base64_img": base64_img})

    def post(self, request):
        """对验证码进行校验"""
        verification_code = request.POST.get('verification_code')
        print(verification_code)
        print(request.session.get('verification_code'))
        if verification_code != request.session.get('verification_code'):
            message = 'verification error.'
            return JsonResponse({'code': 8301, 'message': message})
        return JsonResponse({'code': 200, 'message': 'verify success!'})


# http://www.beiwangyigou.com/account/register
class Register(View):
    def get(self, request):
        return render(request, template_name='account/register.html')

    def post(self, request):
        """处理用户注册"""
        # 接收数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        errors = {}
        # 数据校验  用户名，密码，邮箱，验证码
        if not username:
            code = 8201
            message = 'user cannot be empty.'
        if not password:
            code = 8202
            message = 'password cannot be empty.'
        if not email:
            code = 8203
            message = 'email cannot be empty.'
        elif User.objects.filter(email=email).first():
            code = 8204
            message = 'The email used has been registered.'

        # 思考：上面的数据检验完善吗？还需要校验哪些数据呢？
        if errors:
            return JsonResponse({'code': code, 'message': message})

        # 从request的session中提取保存的code，然后与用户提交的验证码进行比较

        # 保存用户
        user = User(name=username, passwd=make_password(password), email=email)

        # 发送激活邮件
        s = Serializer(settings.SECRET_KEY, 60 * 60)
        # dumps可以把字符串、字典、列表对象序列化为json字符串
        token = s.dumps(email)
        send_active_email(token, email)
        user.save()
        return JsonResponse({"message": "register success!"})


def active_user(request, token):
    print(token)
    serializer = Serializer(settings.SECRET_KEY, expires_in=60 * 60)
    try:
        email = serializer.loads(token)
    except SignatureExpired:
        code = 8101
        return JsonResponse(
            {'code': code, 'message': 'Activation code has expired!'})

    user = User.objects.filter(email=email).first()
    if user:
        user.is_active = True
        user.save()
        return JsonResponse({'code': 200, 'message': 'Active success!'})


class Login(View):

    # def get(self,request):
    #     resp = JsonResponse({'msg':'ok'})
    #     resp.set_cookie('test','hello!')
    #     return resp

    def post(self, request):

        username = request.POST.get('username')
        password = request.POST.get('password')
        remember = request.POST.get('remember')
        vcode = request.POST.get('verifycode')

        # 数据校验
        code = 200
        message = 'ok'
        if not username:
            code = 8001
            message = 'username cannot be empty.'
        if not password:
            code = 8002
            message = 'password cannot be empty.'
        if not vcode:
            code = 8003
            message = 'vode cannot be empty.'
        elif vcode != request.session.get('verification_code'):
            code = 8004
            message = 'verification code is wrong！'

        # if message!='ok':
        #     return JsonResponse({'code':code,'message':message})

        user = User.objects.filter(name=username).first()

        if user:
            if not check_password(password, user.passwd):
                code = '8401'  # 密码错误
                message = 'password error!'
                return JsonResponse({'code': code, 'message': message})
            code = 200
            message = 'login success！'
            next = reverse('account:index')
            resp = JsonResponse(
                {'message': message, 'code': code, 'next_url': next})

            if remember is 'true':
                resp.set_cookie('username', username, max_age=7 * 24 * 3600)
            else:
                resp.delete_cookie('username')

            request.session['is_login'] = True

            request.session['username'] = username
            request.session['user_id'] = user.id
            print(request.session)

            return resp

        return JsonResponse({'message': message, 'code': code})


class Logout(View):
    def post(self, request):
        request.session.flush()
        return redirect(reverse('account:index'))


class Address(View):
    @login_required
    def get(self, request):
        user_id = request.session.get('user_id')
        addr = UserAddress.objects.get_default(user_id)
        addresses = UserAddress.objects.all()

        return JsonResponse({'addresses': [addr.to_dict for addr in addresses]})

    @login_required
    def post(self, request):
        recipient = request.POST.get('username')
        addr = request.POST.get('address')
        zip_code = request.POST.get('zip_code')
        phone = request.POST.get('phone')
        UserAddress.objects.add_address(request.session.get('user_id'), addr,
                                        zip_code, phone)

        # 数据校验
        pass

        return JsonResponse({'code': 200, 'msg': 'ok'})


class PermissionAdmin(View):
    def get(self, request):
        """获得权限"""
        return JsonResponse({'msg': 'todo'})

    def post(self, request):
        """添加权限"""
        content_type = ContentType.objects.get_for_model(UserAddress)
        permission = Permission.objects.create(codename='modify_address',
                                               name='修改地址',
                                               content_type=content_type)
        return JsonResponse({'msg':'ok'})

